//
//  DUPlayView.m
//  APP
//
//  Created by duyujin1 on 2021/9/7.
//

#import "DUPlayView.h"
#import <Masonry.h>

@interface DUPlayView ()
@property(nonatomic,strong) UIView * bgView;
@property(nonatomic,strong) AVPlayer * player;
@property(nonatomic,strong) UISlider * progressSlider;
@property(nonatomic,strong) UIButton * playButton;
@end

@implementation DUPlayView

-(instancetype)initWithFrame:(CGRect)frame{
    if(self=[super initWithFrame:frame]){
        [self setUI];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(moviePlayDidEnd) name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];
    }
    return self;
}

+(DUPlayView *)sharePlayer{
    static AVPlayer * player;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        player=[[AVPlayer alloc] init];
    });
    return player;
}


-(void)setUI{
    [self addSubview:self.bgView];
    [self.bgView addSubview:self.playButton];
    [self.bgView addSubview:self.progressSlider];
    [self.playButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.bottom.mas_equalTo(self.bgView);
        make.width.mas_equalTo(50);
    }];
    [self.progressSlider mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.bottom.mas_equalTo(self.bgView);
        make.left.mas_equalTo(self.playButton);
    }];
}

-(void)setPlayer:(AVPlayer *)myPlayer{
    AVPlayerLayer * playerLayer=(AVPlayerLayer *)[DUPlayView sharePlayer];
    [playerLayer setPlayer:myPlayer];
}

+(Class)layerClass{
    return [AVPlayerLayer class];
}

-(void)playWithUrl:(NSURL *)url{
    AVURLAsset * asset=[AVURLAsset assetWithURL:url];
    __weak typeof(self) weakSelf = self;
    [asset loadValuesAsynchronouslyForKeys:[NSArray arrayWithObject:@"tracks"] completionHandler:^{
        __strong typeof(weakSelf) strongSelf = weakSelf;
        //获取资源加载状态
        AVKeyValueStatus status=[asset statusOfValueForKey:@"tracks" error:nil];
        if(status==AVKeyValueStatusLoaded){
            //将加载好的资源放在AVPlayerItem中
            AVPlayerItem * item=[AVPlayerItem playerItemWithAsset:asset];
            strongSelf.player=[[AVPlayer alloc] initWithPlayerItem:item];
            //将播放器与视图关联
            [strongSelf setPlayer:strongSelf.player];
            [strongSelf.player play];
            //实时显示播放进度,异步获取
            [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:dispatch_get_global_queue(0, 0) usingBlock:^(CMTime time) {
                //获取当前播放时间
                CMTime current=strongSelf.player.currentItem.currentTime;
                //获取总时间
                CMTime dur=strongSelf.player.currentItem.duration;
                //转化为秒
                float pro=CMTimeGetSeconds(current)/CMTimeGetSeconds(dur);
                dispatch_async(dispatch_get_main_queue(), ^{
                    if(pro>=0&&pro<=1){
                        strongSelf.progressSlider.value=pro;
                    }
                });
            }];
        }
    }];
}

-(void)_playButtonClick:(UIButton *)btn{
    if(btn.selected==YES){
        //暂停按钮被点击
        if(_player){
            [_player pause];
        }
        btn.selected=NO;
        return;
    }
    //播放按钮被点击
    if(_player){
        [_player play];
    }
    btn.selected=YES;
    return;
}


-(void)_progressChange:(UISlider *)slider{
    if(!_player){
        return ;
    }
    CMTime dur=_player.currentItem.duration;
    float current=_progressSlider.value;
    //将总时长当前进度转化为CMTime
    [_player seekToTime:CMTimeMultiplyByFloat64(dur, current)];
}

-(void)releasePlayer{
    if(_player){
        [_player pause];
        _player=nil;
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    for(int i=0;i<[_bgView.subviews count];i++){
        UIView *view=[_bgView.subviews objectAtIndex:i];
        [view removeFromSuperview];
        view=nil;
        i--;
    }
    [_bgView removeFromSuperview];
    _bgView=nil;
}

-(void)moviePlayDidEnd{
    NSLog(@"");
}

#pragma mark-getter

-(UIView *)bgView{
    if(!_bgView){
        _bgView=[[UIView alloc] initWithFrame:self.bounds];
        _bgView.backgroundColor=[UIColor lightGrayColor];
    }
    return _bgView;
}

-(UIButton *)playButton{
    if(!_playButton){
        _playButton=[[UIButton alloc] initWithFrame:CGRectZero];
        _playButton.backgroundColor=[UIColor whiteColor];
        _playButton.selected=YES;
        [_playButton setTitle:@"play" forState:UIControlStateNormal];
        [_playButton setTitle:@"pause" forState:UIControlStateSelected];
        [_playButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_playButton addTarget:self action:@selector(_playButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _playButton;
}

-(UISlider *)progressSlider{
    if(!_progressSlider){
        _progressSlider=[[UISlider alloc] initWithFrame:CGRectZero];
        _progressSlider.minimumValue=0.0;
        _progressSlider.maximumValue=1.0;
        [_progressSlider addTarget:self  action:@selector(_progressChange:) forControlEvents:UIControlEventValueChanged];
    }
    return _progressSlider;
}

@end
